//
//  USChatThemeController.m
//  us
//
//  Created by karry on 2025/4/12.
//

#import "USChatThemeController.h"

#import "USChatThemeColorCell.h"

#import "USMediaPickerManager.h"
#import "USMediaUploadManager.h"
#import "USPhotoUploadTool.h"
#import "USChatTheme.h"

@interface USChatThemeController ()<UICollectionViewDelegate,UICollectionViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) NSMutableArray <NSString *>*themeColorList;

@property (nonatomic, assign) NSInteger selectIndex;

@property (nonatomic, assign) BOOL selectCustom;//是否选择自定义图片

@property (nonatomic, strong) USMediaResult *media;

@end

@implementation USChatThemeController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.navigationItem.title = @"默认格子";
    self.view.backgroundColor = [UIColor subMainBgColor];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"ic_gouzi"] style:UIBarButtonItemStylePlain target:self action:@selector(saveTheme:)];

    [self setUpView];

}

- (void)setUpView {
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.strokeColor = UIColor.mi_3_color.CGColor;
    shapeLayer.lineWidth = 2;
    shapeLayer.lineCap = kCALineCapRound;
    shapeLayer.lineDashPattern = @[@8, @8];

    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(16, 0)];
    [path addLineToPoint:CGPointMake(ScreenWidth - 32, 2)];
    
    shapeLayer.path = path.CGPath;
    [self.lineBgView.layer addSublayer:shapeLayer];
    
 
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize = CGSizeMake(84 , 110);
    layout.minimumInteritemSpacing = 24;
    layout.minimumLineSpacing = 24;
    layout.sectionInset = UIEdgeInsetsMake(16, 32, 16, 32);
    self.collectionView.collectionViewLayout = layout;
    self.collectionView.alwaysBounceHorizontal = NO;
    self.collectionView.alwaysBounceVertical = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
     [self.collectionView registerClass:[USChatThemeColorCell class] forCellWithReuseIdentifier:@"USChatThemeColorCell"];
 
    
    if (USUser.user.imBgType == 2 && USUser.user.imPhoto.length > 0) {
        self.bgImgView.hidden = NO;
        self.selectCustom = YES;
        [self.bgImgView sd_setImageWithURL:[NSURL URLWithString:USUser.user.imPhoto]];
    }else if (USUser.user.imBgType == 1 && USUser.user.imColor.length > 0) {
        self.chatBgView.backgroundColor = [UIColor jk_colorWithHexString:USUser.user.imColor];
    }else {
        self.bgImgView.hidden = NO;
        self.bgImgView.image = [USChatTheme defaultTheme].bgImage;
    }
     

    for (int i = 0; i < self.themeColorList.count; i++) {
        
        if ([USUser.user.imColor isEqualToString:self.themeColorList[i]]) {
            self.selectIndex = i;
            break;
        }
       
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:self.selectIndex inSection:0]
                                    atScrollPosition:UICollectionViewScrollPositionNone
                                            animated:YES];
        
        [self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:self.selectIndex inSection:0] animated:NO scrollPosition:UICollectionViewScrollPositionNone];
        
    });
    
}
- (void)startUpload{
    [self.indicator startAnimating];
    UIBarButtonItem *loadingItem = [[UIBarButtonItem alloc] initWithCustomView:self.indicator];
    self.navigationItem.rightBarButtonItem = loadingItem;
    self.view.userInteractionEnabled = NO; // 禁用整个页面操作

    
}
- (void)endUpLoad{
    self.navigationItem.rightBarButtonItem = self.doneItem;
    [self.indicator stopAnimating];
    self.view.userInteractionEnabled = YES;
}

#pragma mark - UIImagePickerControllerDelegate,UINavigationControllerDelegate;

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {

    NSString *mediaType = info[UIImagePickerControllerMediaType];

    if ([mediaType isEqualToString:UTTypeImage.identifier]) {
        // 图片
        UIImage *image = info[UIImagePickerControllerOriginalImage];
        NSData *imageData = UIImageJPEGRepresentation(image, 1);
        NSString *tmpPath = [USPhotoUploadTool imagePathWithUUID:NSUUID.UUID.UUIDString];
        [imageData writeToFile:tmpPath atomically:YES];
        
        
        USMediaResult *item = [[USMediaResult alloc] init];
        item.uuid = [[NSUUID UUID] UUIDString];
        item.filePath = tmpPath;
        item.type = USMediaTypeImage;
        item.recordDate = (NSInteger)[[NSDate date] timeIntervalSince1970];
        item.customDate = (NSInteger)[[NSDate date] timeIntervalSince1970];
        
        
        self.media = item;
        self.selectCustom = YES;
        
        self.bgImgView.hidden = NO;
        self.bgImgView.image = [UIImage imageWithContentsOfFile:tmpPath];
     
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - action

- (IBAction)customBgAction:(id)sender {

    @weakify(self)
    DTItem *item0 = [DTItem itemWithTitle:@"拍摄" image:[UIImage imageNamed:@"icon-camera-22"] tag:0 identifier:nil handle:^(DTItem *item) {
        @strongify(self)
        [self takePhotoAction];
    }];
    
    DTItem *item1 = [DTItem itemWithTitle:@"相册" image:[UIImage imageNamed:@"icon-photo-22"] tag:0 identifier:nil handle:^(DTItem *item) {
        @strongify(self)
        [self presentImagePicker];
    }];
 
    DTTargetView *view = [[DTTargetView alloc] initWithTargetView:sender item:@[item0,item1]];
    
    [view show];
    
}
- (void)takePhotoAction{
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.delegate = self;
        picker.allowsEditing = NO; // 是否允许编辑
        picker.showsCameraControls = YES;
        picker.mediaTypes = @[UTTypeImage.identifier];
        [self presentViewController:picker animated:YES completion:nil];
    } else {
        [self.view us_makeAlert:@"当前设备不支持拍照" subTitle:nil];
    }
    
}

- (void)presentImagePicker{
    [USFeedbackTool impactSoft];

    @weakify(self)
    [USMediaPickerManager presentPickerFrom:self type:USPickerMediaType_Image limit:1 didFinishPicking:^{
//        @strongify(self)
//        [self startUpload];
    } progressHandler:^(NSInteger current, NSInteger total) {
   
        
    } completion:^(NSArray<USMediaResult *> * _Nonnull results) {
        @strongify(self)
//        [self endUpLoad];
 
        self.media = results.firstObject;
        self.selectCustom = YES;
        self.bgImgView.hidden = NO;
        self.bgImgView.image = [UIImage imageWithContentsOfFile:results.firstObject.filePath];
        
    }];
    
}


- (void)saveTheme:(id)sender{
    [USFeedbackTool notifySuccess];
    [self startUpload];

    if (self.selectCustom && self.media) {
        [self uploadMedia];
    }else{
        [self updateImBg:nil];
    }
    
}

- (void)uploadMedia{
 
    NSString * albumFirstDirectory = [NSString stringWithFormat:@"%@/%@",[USUser user].sharedSpaceId,NSUUID.UUID.UUIDString];
    [USMediaUploadManager uploadImages:@[self.media] albumFirstDirectory:albumFirstDirectory albumSecondDirectory:@"video" progress:^(NSInteger current, NSInteger total) {
         
    } success:^(NSArray<USPhotoModel *> * _Nonnull models) {
        
        [self updateImBg:models.firstObject];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (void)updateImBg:(USPhotoModel *)photoModel{
 
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    NSString *color = self.themeColorList[self.selectIndex];
    if (self.selectCustom) {
        [params setObject:@(2) forKey:@"imBgType"];
        if (photoModel) {
            [params setObject:photoModel.cosUrl?:@"" forKey:@"imPhoto"];
        }
    }else{
        if (color.length == 0) {
            [params setObject:@(0) forKey:@"imBgType"];
         }else{
            [params setObject:@(1) forKey:@"imBgType"];
            [params setObject:color forKey:@"imColor"];
        }
     
    }
  

    [[EMNetWork shareManager] em_post:API_EditUser
                               params:params
                                  hud:nil
                           showError:YES
                              success:^(EMApiModel *api) {
        [self.view endEditing:YES];
        [self endUpLoad];

        if (!api.success) {
            return;
        }
        USUser *user = [USUser user];
        
        if (self.selectCustom) {
            user.imBgType = 2;
            if (photoModel) {
                user.imPhoto = photoModel.cosUrl?:@"";
            }
        }else{
            if (color.length == 0) {
                user.imBgType = 0;
                
            }else{
                user.imBgType = 1;
                user.imColor = color;
            }
            
        }
        
        [USUser saveUser:user];
 
        [self.navigationController popViewControllerAnimated:YES];
    } fail:^{
        [self endUpLoad];

    }];
}

- (NSMutableArray <NSString *>*)themeColorList {
   if(_themeColorList == nil) {
       _themeColorList = [NSMutableArray array];

       NSArray *colorList = @[@"",@"#EFEFE8",@"#DFD3D7",@"#DEE3DD",@"#EAD0D5",@"#EDE6F6",@"#BFCAD6",@"#EEECEC"];
    
       [_themeColorList addObjectsFromArray:colorList];
   }
   return _themeColorList;
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(nonnull UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
         
    return self.themeColorList.count;
 
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return YES;
    
}


- (nonnull __kindof UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    
    USChatThemeColorCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"USChatThemeColorCell" forIndexPath:indexPath];
    if (indexPath.row == 0) {
        cell.themeImgView.image = [USChatTheme defaultTheme].bgImage;
        cell.themeImgView.hidden = NO;
        cell.themeColorView.hidden = YES;
    }else {
        NSString *color = self.themeColorList[indexPath.row];
        cell.themeColorView.backgroundColor = [UIColor jk_colorWithHexString:color];
        cell.themeImgView.hidden = YES;
        cell.themeColorView.hidden = NO;
    }

    return cell;
    
    
}
 

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    self.media = nil;
    self.selectCustom = NO;
    
    self.selectIndex = indexPath.row;
    
    if (indexPath.row == 0) {
        //默认格子图
        self.bgImgView.hidden = NO;
        self.bgImgView.image = [USChatTheme defaultTheme].bgImage;
    }else {
        self.bgImgView.hidden = YES;
        NSString *color = self.themeColorList[indexPath.row];
        self.chatBgView.backgroundColor = [UIColor jk_colorWithHexString:color];
    }
}


@end
